// stores/useTodosStore.ts
import { create } from "zustand";
import { useShallow } from "zustand/shallow";
import { devtools, persist } from "zustand/middleware";
import type { TodoItem, FilterType } from "@/stores/mobx/TodosStore/index.d";

interface TodosState {
  todos: TodoItem[];
  filter: FilterType;
}

interface TodosActions {
  // Actions
  addTodo: (text: string) => void;
  removeTodo: (id: string) => void;
  toggleTodo: (id: string) => void;
  setFilter: (filter: FilterType) => void;
  clearCompleted: () => void;
  toggleAll: () => void;

  // 计算属性 (通过 getter 函数实现)
  getFilteredTodos: () => TodoItem[];
  getActiveTodoCount: () => number;
  //   getHasCompleted: () => boolean;
  //   getAllCompleted: () => boolean;
}

type TodosStore = TodosState & TodosActions;

// 创建 store
export const useTodosStore = create<TodosStore>()(
  devtools(
    persist(
      (set, get) => ({
        // 初始状态
        todos: [],
        filter: "All",

        // Actions
        addTodo: (text: string) => {
          if (text.trim()) {
            const newTodo: TodoItem = {
              id: Date.now().toString(),
              text: text.trim(),
              completed: false,
              createdAt: new Date(),
            };

            set((state) => ({
              todos: [...state.todos, newTodo],
            }));
          }
        },

        removeTodo: (id: string) => {
          set((state) => ({
            todos: state.todos.filter((todo) => todo.id !== id),
          }));
        },

        toggleTodo: (id: string) => {
          set((state) => ({
            todos: state.todos.map((todo) =>
              todo.id === id ? { ...todo, completed: !todo.completed } : todo
            ),
          }));
        },

        setFilter: (filter: FilterType) => {
          set({ filter });
        },

        clearCompleted: () => {
          set((state) => ({
            todos: state.todos.filter((todo) => !todo.completed),
          }));
        },

        toggleAll: () => {
          set((state) => {
            const allCompleted =
              state.todos.length > 0 &&
              state.todos.every((todo) => todo.completed);

            return {
              todos: state.todos.map((todo) => ({
                ...todo,
                completed: !allCompleted,
              })),
            };
          });
        },

        // 计算属性 - 通过函数实现
        getFilteredTodos: () => {
          const { todos, filter } = get();
          switch (filter) {
            case "Active":
              return todos.filter((todo) => !todo.completed);
            case "Completed":
              return todos.filter((todo) => todo.completed);
            default:
              return todos;
          }
        },

        getActiveTodoCount: () => {
          const { todos } = get();
          return todos.filter((todo) => !todo.completed).length;
        },

        getHasCompleted: () => {
          const { todos } = get();
          return todos.some((todo) => todo.completed);
        },

        getAllCompleted: () => {
          const { todos } = get();
          return todos.length > 0 && todos.every((todo) => todo.completed);
        },
      }),
      {
        name: "todos-storage",
        partialize: (state) => ({
          todos: state.todos,
          filter: state.filter,
        }),
      }
    ),
    {
      name: "TodosStore",
    }
  )
);

export const useFilter = () => useTodosStore((state) => state.filter);

export const useTodosStoreActions = () =>
  useTodosStore(
    useShallow((state) => ({
      addTodo: state.addTodo,
      removeTodo: state.removeTodo,
      toggleTodo: state.toggleTodo,
      setFilter: state.setFilter,
      clearCompleted: state.clearCompleted,
      toggleAll: state.toggleAll,
    }))
  );

export const useTodosStoreComputed = () =>
  useTodosStore(
    useShallow((state) => ({
      getFilteredTodos: state.getFilteredTodos,
      getActiveTodoCount: state.getActiveTodoCount,
    //   getHasCompleted: state.getHasCompleted,
    //   getAllCompleted: state.getAllCompleted,
    }))
  );